package com.smartfast4j.backend.common.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import java.util.TreeSet;

/**
 * Created by gacl on 2017/9/7.
 */
public class RedisOperator implements IRedisOperator {

    public final static Logger logger = LoggerFactory.getLogger(RedisOperator.class);

    private JedisCluster jedisCluster;

    public RedisOperator(JedisCluster jedisCluster){
        this.jedisCluster = jedisCluster;
    }

    @Override
    public TreeSet<String> clusterKeys(String pattern) {
        logger.debug("Start getting clusterKeys...");
        TreeSet<String> keys = new TreeSet<>();
        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
        for(String k : clusterNodes.keySet()){
            logger.debug("Getting clusterKeys from: {}", k);
            JedisPool jp = clusterNodes.get(k);
            Jedis connection = jp.getResource();
            try {
                keys.addAll(connection.keys(pattern));
            } catch(Exception e){
                logger.error("Getting clusterKeys error: {}", e);
            } finally{
                logger.debug("Connection closed.");
                connection.close();//用完一定要close这个链接！！！
            }
        }
        logger.debug("Keys gotten!");
        return keys;
    }

    @Override
    public void clusterFlushDB() {
        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
        for (Object k : clusterNodes.keySet()) {
            JedisPool jp = clusterNodes.get(k);
            Jedis connection = jp.getResource();
            try {
                connection.flushDB();
            } catch (Exception e) {
                logger.error("clusterFlushDB error: {}", e);
            } finally {
                logger.debug("Connection closed.");
                connection.close();//用完一定要close这个链接！！！
            }
        }
    }

    @Override
    public Long clusterDbSize() {
        Long total = 0L;
        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
        for (Object k : clusterNodes.keySet()) {
            JedisPool jp = clusterNodes.get(k);
            Jedis connection = jp.getResource();
            try {
                total += connection.dbSize();
            } catch (Exception e) {
                logger.error("connection.dbSize() error: {}", e);
            } finally {
                connection.close();//用完一定要close这个链接！！！
            }
        }
        return total;
    }
}
